package org.example.practice;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/request2")
@RestController
public class RequestController2 {
    //读取cookie
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request){
        Cookie[] cookies=request.getCookies();
        if (cookies!=null){
            for (Cookie cookie : cookies){
                System.out.println(cookie.getName()+":"+cookie.getValue());
            }
        }
        return "成功获取cookie";
    }
    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("class") String className){
        return "className:"+className;
    }
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request,String name){
        HttpSession session=request.getSession();
        session.setAttribute("name",name);
        session.setAttribute("age",15);
        System.out.println(session.getAttribute("name"));
        return "成功设置session";
    }
    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session){
        //获取用户信息
        String name = (String)session.getAttribute("name");
        Integer age = (Integer) session.getAttribute("age");
        return "从session中获取数据, name:"+ name + ",age:"+ age;
    }
    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute("name") String name){
        //获取用户信息
        return "从session中获取数据, name:"+ name;
    }
    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request){
        String header = request.getHeader("User-Agent");
        return "User-Agent:"+header;
    }
    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent){
//        String userAgent = request.getHeader("User-Agent");
        return "从header中获取数据, userAgent:"+ userAgent ;
    }
}
